package me.zbl;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Path;

import static java.lang.System.*;
import static java.nio.file.Files.*;
import static java.nio.file.Paths.get;

/**
 * @author zhengbaole
 */
public class Bootstrap {

    /**
     * 0: file location of dictionary text file
     * <p>
     * 1: content of last line to be deleted
     */
    public static void main(String[] args) {
        Bootstrap app = new Bootstrap();
        try {
            app.readAndWrite(args);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void readAndWrite(String[] args) throws IOException {
        if (2 > args.length) {
            err.println("File location or content not specified. ");
            return;
        }
        String file = args[0];
        String target = args[1];
        Path path = get(file);
        out.println("Searching target in this file... ");
        BufferedReader br = newBufferedReader(path);
        String line;
        boolean found = false;
        int index = -1;
        while (null != (line = br.readLine())) {
            index++;
            if (target.equals(line)) {
                out.println("Target line was found! ");
                found = true;
                break;
            }
        }
        if (-1 == index) {
            err.println("This file is empty. ");
        }
        if (!found) {
            err.println("Target line was not found in this file. ");
            return;
        }
        String prefix = "dict-tmp-";
        Path tmpPath = createTempFile(prefix, String.valueOf(currentTimeMillis()));
        BufferedWriter bw = newBufferedWriter(tmpPath);
        br = newBufferedReader(path);
        int cursor = 0;
        out.println("Writing result to this file... ");
        while (null != (line = br.readLine())) {
            if (index < cursor) {
                bw.write(line);
                bw.newLine();
            }
            cursor++;
        }
        bw.flush();
        delete(path);
        move(tmpPath, path);
        out.println("Result was saved successfully. ");
    }
}
